<template>
  <div class="sort-list-container">
     <GoodsItem v-for="good in CategoryGoodsList" :key="good.id" :good='good'/>
  </div>
  <XtxInfiniteLoad :isLoading="isLoading" :isFinished="isFinished" @load="loadFn"/>
</template>
<script>
import { findSubCategoryGoods } from '@/api/category'
import { onMounted, ref, watch, inject } from 'vue'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import GoodsItem from '@/views/Category/components/goods-item'
export default {
  components: {
    GoodsItem
  },
  setup () {
    const CategoryGoodsList = ref([])
    const route = useRoute()
    let reqParams = {
      page: 1,
      pageSize: 20,
      categoryId: route.params.id,
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    }
    async function getCategoryGoodsList () {
      // 加载首页数据的时候 先把上拉加载功能关掉
      isLoading.value = true
      const res = await findSubCategoryGoods(reqParams)
      console.log(res)
      CategoryGoodsList.value = res.data.result.items
    }
    onMounted(() => {
      getCategoryGoodsList()
      console.log(reqParams.categoryId)
    })
    onBeforeRouteUpdate(() => {
      getCategoryGoodsList()
    })
    // 引入顶层组件提供的额外参数数据
    const filterData = inject('filterData')
    watch(
      () => { return filterData },
      () => {
        reqParams = { ...reqParams, ...filterData }
        getCategoryGoodsList()
      },
      { deep: true }
    )
    // 加载下一页
    const isLoading = ref(false) // 是否加载中
    const isFinished = ref(false) // 是否加载完毕
    async function loadFn () {
      isLoading.value = true
      reqParams.page++ // 页码加加
      const res = await findSubCategoryGoods(reqParams)
      if (res.data.result.items.length === 0) {
        isFinished.value = true
      }
      CategoryGoodsList.value = [...CategoryGoodsList.value, ...res.data.result.items]
      isLoading.value = false
    }
    return {
      CategoryGoodsList,
      isLoading,
      isFinished,
      loadFn
    }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.goods-item {
  display: block;
  width: 220px;
  padding: 20px 30px;
  text-align: center;
  img {
    width: 160px;
    height: 160px;
  }
  p {
    padding-top: 10px;
  }
  .name {
    font-size: 16px;
  }
  .desc {
    color: #999;
    height: 29px;
  }
  .price {
    color: @priceColor;
    font-size: 20px;
  }
}
</style>
